/** software/vulnerabilities/:cve > Vulnerable OS section */

import React, { useCallback, useMemo } from "react";
import { Row } from "react-table";
import { InjectedRouter } from "react-router";

import PATHS from "router/paths";
import { getPathWithQueryParams } from "utilities/url";
import { IVulnerabilityResponse } from "services/entities/vulnerabilities";
import Card from "components/Card";
import TableContainer from "components/TableContainer";
import { DEFAULT_PAGE_SIZE } from "components/TableContainer/TableContainer";
import TableCount from "components/TableContainer/TableCount";

import generateColumnConfigs from "./SwVulnOSTableConfig";

const baseClass = "software-vuln-os-versions";

interface IRowProps extends Row {
  original: {
    os_version_id?: string;
  };
}

interface ISoftwareVulnOSVersions {
  osVersions: IVulnerabilityResponse["os_versions"];
  isPremiumTier: boolean;
  router: InjectedRouter;
  teamIdForApi?: number;
}

const SoftwareVulnOSVersions = ({
  osVersions,
  isPremiumTier,
  router,
  teamIdForApi,
}: ISoftwareVulnOSVersions) => {
  const columnConfigs = useMemo(
    () => generateColumnConfigs(isPremiumTier, router, teamIdForApi),
    [isPremiumTier, router, teamIdForApi]
  );

  const handleRowSelect = (row: IRowProps) => {
    if (row.original.os_version_id) {
      const softwareOsVersionId = Number(row.original.os_version_id);

      const softwareOsDetailsPath = getPathWithQueryParams(
        PATHS.SOFTWARE_OS_DETAILS(softwareOsVersionId),
        { team_id: teamIdForApi }
      );

      router.push(softwareOsDetailsPath);
    }
  };

  const renderVulnerableOSCount = useCallback(() => {
    return <TableCount name="items" count={osVersions?.length} />;
  }, [osVersions?.length]);

  const renderVulnerableOSTable = () => {
    return (
      <TableContainer
        columnConfigs={columnConfigs}
        data={osVersions}
        defaultSortHeader="hosts"
        defaultSortDirection="desc"
        isClientSidePagination
        isLoading={false} // not rendered otherwise
        emptyComponent={() => <></>}
        showMarkAllPages={false}
        isAllPagesSelected={false}
        disableMultiRowSelect
        hideFooter={osVersions.length <= DEFAULT_PAGE_SIZE}
        onSelectSingleRow={handleRowSelect}
        renderCount={renderVulnerableOSCount}
      />
    );
  };

  return (
    <Card borderRadiusSize="xxlarge" className={baseClass}>
      <h2>Vulnerable OS</h2>
      {renderVulnerableOSTable()}
    </Card>
  );
};

export default SoftwareVulnOSVersions;
